package Practice6_Internet.P2_TCP;

import Utils.io.IOUtils;
import org.junit.jupiter.api.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class PracticeTest03 {
    @Test
    public void client() throws IOException {
        try (Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
             OutputStream os = socket.getOutputStream();
             FileInputStream fis = new FileInputStream(new File("./src/test/resources/img104.jpg"))) {
            IOUtils.inputStream2OutputStream(fis, os);
            // 关闭socket输出流
            socket.shutdownOutput();

            // 接收来自服务器端的数据，并显示到控制台
            try (InputStream is = socket.getInputStream();
                 /*ByteArrayOutputStream baos = IOUtils.inputStream2ByteArrayOutputStream(is)*/) {
//                System.out.println(baos.toString());
                System.out.println(IOUtils.inputStream2String(is));
            }
        }
    }

    @Test
    public void server() throws IOException {
        try (ServerSocket serverSocket = new ServerSocket(9090);
             Socket socket = serverSocket.accept();
             InputStream is = socket.getInputStream();
             FileOutputStream fos = new FileOutputStream("./src/test/resources/img104_New.jpg")) {
            IOUtils.inputStream2OutputStream(is, fos);

            System.out.println("图片传输完成");

            // 服务器端给予客户端反馈
            try (OutputStream os = socket.getOutputStream()) {
                os.write("文件已收到".getBytes(StandardCharsets.UTF_8));
            }
        }
    }
}
